//
//  carEndTheTripViewController.m
//  QXDLLOrdersModule
//
//  Created by DL on 17/1/5.
//  Copyright © 2017年 DLL. All rights reserved.
//

#import "carEndTheTripViewController.h"
#import "paymentOrderDetailsViewController.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "carEndTheTripVCCell.h"
#import "DLLApiManager.h"
#import "HeaderMacro.h"
#import "BillingRulesVC.h"
#import <SDWebImage/SDWebImage-umbrella.h>
#import <MJRefresh/MJRefresh.h>
#import "DetailsOfChargesModel.h"
#import <QXDataManager/QXDataManager.h>
#import "NotificationNameManager.h"
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>
#import "OrderClosingManager.h"
#import "AppManager.h"
#import "AppInfoModel.h"
@interface carEndTheTripViewController ()<UITableViewDelegate , UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIBarButtonItem *leftBarButtonItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightBarButtonItem;
/// 头像
@property (weak, nonatomic) IBOutlet UIImageView *heardImageView;
/// 手机尾号
@property (weak, nonatomic) IBOutlet UILabel *phoneTailNumberLabel;
/// 拨打电话
@property (weak, nonatomic) IBOutlet UIButton *callPhoneButton;
/// 总价格
@property (weak, nonatomic) IBOutlet UILabel *fareLabel;

/// 计价规则图片
@property (weak, nonatomic) IBOutlet UIImageView *pricingRulesImageView;
/// 确认费用
@property (weak, nonatomic) IBOutlet UIButton *confirmFareButton;

@property (weak, nonatomic) IBOutlet UITableView *tableView;


/**
 数据源
 */
@property(nonatomic , strong) NSMutableArray *dataSource;

@property(nonatomic , strong) UIAlertController *alertVC;


@end

@implementation carEndTheTripViewController
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"carEndTheTripViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationAction];
    

    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf requestDetailsOfCharges];
    }];
    [self.tableView.mj_header beginRefreshing];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    __weak typeof(self) weakSelf = self;
    [[OrderClosingManager shareManager] openNotificationWithOrderUuid:self.ordersDetailsModel.uuid receivedNotification:^(NSNotification *aNotification) {
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.alertVC dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
}


- (void)initializationAction {
    
    self.heardImageView.layer.cornerRadius = self.heardImageView.frame.size.height / 2.0;
    self.heardImageView.layer.masksToBounds = YES;
    
    if (![self.userPassengerModel.face isKindOfClass:[NSNull class]] && self.userPassengerModel.face.length > 0) { // 如果值非空,并且长度大于0
        
        NSURL *url = [NSURL URLWithString:self.userPassengerModel.face];
        [self.heardImageView sd_setImageWithURL:url placeholderImage:[QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"]];
    }else {
        
        self.heardImageView.image = [QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"];
    }
    
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    
    self.fareLabel.text = [NSString stringWithFormat:@"--元"];
    self.leftBarButtonItem.image = [QXDriverConfiguration imageWithName:@"nav_icon_back_white"];
    self.rightBarButtonItem.image = [QXDriverConfiguration imageWithName:@"nav_icon_more"];
    [self.callPhoneButton setImage:[QXDriverConfiguration imageWithName:@"public_call2"] forState:UIControlStateNormal];
    self.pricingRulesImageView.image = [QXDriverConfiguration imageWithName:@"public_icon_jiajiaguize"];
    
    if (self.userPassengerModel.mobile != nil && self.userPassengerModel.mobile.length >= 4) {
        
        NSString *lastNumber = [self.userPassengerModel.mobile substringWithRange:NSMakeRange(self.userPassengerModel.mobile.length - 4, 4)];
        self.phoneTailNumberLabel.text = [NSString stringWithFormat:@"尾号%@" , lastNumber];
    }
    
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
}

#pragma mark -计价规则
- (IBAction)pricingRulesAction:(id)sender {
    
    BillingRulesVC *billingRulesVC = [[BillingRulesVC alloc] init];
    billingRulesVC.title = @"计价规则";
    billingRulesVC.urlString = [NSString stringWithFormat:@"%@%@&orderUuid=%@" , [QXDataManager getValueForKey:ZhuJiDriverServiceUrlKey] , [QXDataManager getValueForKey:QXHtml5Kkey_PriceDescription], self.ordersDetailsModel.uuid];
    [self.navigationController pushViewController:billingRulesVC animated:YES];
}

#pragma mark - 打电话
- (IBAction)callAction:(UIButton *)sender {
    
    NSString *phone = self.userPassengerModel.mobile;
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url];
    }
}


#pragma mark -确认费用
- (IBAction)confirmFareAction:(UIButton *)sender {
    
    sender.userInteractionEnabled = NO;
    [self confirmFareRequest];
}

#pragma mark -费用有误
- (IBAction)costIsIncorrectAction:(id)sender {
    
    NSString *title = @"";
    AppInfoModel *appInfoModel = [[AppManager shareManager] getAppInfo];
    if (appInfoModel.AppDriverType == DriverTypeCargoTaxi || appInfoModel.AppDriverType == DriverTypeHouseMoving || appInfoModel.AppDriverType == DriverTypeRider) { // 货的,搬家,骑手
        
        title = @"若您或用户对费用有异议，可协商后联系客服进行修改";
    }else {
        
        title = @"若您或乘客对费用有异议，可协商后联系客服进行修改";
    }
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:title preferredStyle:(UIAlertControllerStyleAlert)];
    [self.alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self.alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        

        NSString *phone = [QXDataManager getValueForKey:User_KeyWord_CustomerServiceTel];
        
        if (phone != nil) {
            
            NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
            
            NSURL *url = [[NSURL alloc] initWithString:telUrl];
            
            [[UIApplication sharedApplication] openURL:url];
        }
        
    }]];
    
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

#pragma mark -导航条左侧按钮
- (IBAction)leftBarButtonItemAction:(id)sender {
    
    [[OrderClosingManager shareManager] closeNotification];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -导航条右侧按钮
- (IBAction)rightBarButtonAction:(id)sender {
    paymentOrderDetailsViewController *vc = [paymentOrderDetailsViewController shareSelf];
    
    vc.ordersDetailsModel = self.ordersDetailsModel;
    vc.userPassengerModel = self.userPassengerModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [self dealcarEndTheTripVCCellWithTableView:tableView indexPath:indexPath];
    
    return cell;
}

- (carEndTheTripVCCell *)dealcarEndTheTripVCCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    carEndTheTripVCCell *cell = [tableView dequeueReusableCellWithIdentifier:@"carEndTheTripVCCellID" forIndexPath:indexPath];
    
    if (indexPath.row < self.dataSource.count) {
        
        DetailsOfChargesModel *model = self.dataSource[indexPath.row];
        [cell setValueWithDetailsOfChargesModel:model];
    }
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

#pragma mark - 确认费用
- (void)confirmFareRequest {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager confirmFareWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        strongSelf.confirmFareButton.userInteractionEnabled = YES;
        if (NetWork_Success) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ConfirmFare object:nil];
                
                [strongSelf pushIntopaymentOrderDetailsViewController];
                
            });
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.confirmFareButton.userInteractionEnabled = YES;
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}


#pragma mark - 获取当前时间精度: 秒
- (NSTimeInterval)getCurrentTime {
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    
    return timeInterval;
}

- (void)pushIntopaymentOrderDetailsViewController {
   
    paymentOrderDetailsViewController *paymentOrderDetailVC = [paymentOrderDetailsViewController shareSelf];
    paymentOrderDetailVC.title = @"订单详情";
    paymentOrderDetailVC.userPassengerModel = self.userPassengerModel;
    paymentOrderDetailVC.ordersDetailsModel = self.ordersDetailsModel;
    paymentOrderDetailVC.isPoPToRootVC = YES;
    [self.navigationController pushViewController:paymentOrderDetailVC animated:YES];
}

#pragma mark - 获取费用明细
/**
 获取费用明细
 */
- (void)requestDetailsOfCharges {
    

    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    [DLLApiManager driverOrderFareDetailsWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            
            [strongSelf.dataSource removeAllObjects];
            
            if (NetWork_Success) {
                
                NSDictionary *dataDic = data[@"data"];
                
                if ([[dataDic allKeys] containsObject:@"totalFare"]) {
                    
                    strongSelf.fareLabel.text = [NSString stringWithFormat:@"%.1f元" , [dataDic[@"totalFare"] doubleValue]];
                    
                }else {
                    
                    strongSelf.fareLabel.text = [NSString stringWithFormat:@"--元"];
                }
                
                
                if ([[dataDic allKeys] containsObject:@"costItems"]) {
                    
                    NSArray *costItemsArr = dataDic[@"costItems"];
                    if ([costItemsArr isKindOfClass:[NSArray class]]) {
                        
                        if (costItemsArr.count > 0) {
                            
                            for (NSDictionary *costItemsDic in costItemsArr) {
                                
                                DetailsOfChargesModel *model = [DetailsOfChargesModel new];
                                [model setValuesForKeysWithDictionary:costItemsDic];
                                [strongSelf.dataSource addObject:model];
                            }
                        }
                    }
                }
                
            }else {
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                strongSelf.fareLabel.text = [NSString stringWithFormat:@"--元"];
            }
            
            [strongSelf.tableView reloadData];
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
            [strongSelf.tableView.mj_header endRefreshing];
        });
        
    }];
    
}

- (void)dealloc {
    
    NSLog(@"专车确认费用销毁了");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
